package streaming.time.windows.groupWindows;

import streaming.api.beans.SensorReading;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.timestamps.BoundedOutOfOrdernessTimestampExtractor;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.table.api.Slide;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.types.Row;

/**
 * HOP(time_attr，interval，interval)
 * 定义一个滑动窗口，第一个参数是时间字段，第二个参数是窗口滑动步长，第三个是窗口长度
 */
public class WindowTest2 {

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);
        String pathForm = "D:\\IdeaProjects\\springboot-flink-1\\flinkTutorial\\src\\main\\resources\\sensor.txt";
        String fileFormat = "csv";
        DataStream<String> inputStream = env.readTextFile(pathForm);
        DataStream<SensorReading> dataStream = inputStream.map(line -> {
            String[] fields = line.split(",");
            return new SensorReading(fields[0], new Long(fields[1]), new Double(fields[2]));
        }).assignTimestampsAndWatermarks(new BoundedOutOfOrdernessTimestampExtractor<SensorReading>(Time.seconds(2)) {
            @Override
            public long extractTimestamp(SensorReading element) {
                return element.getTimestamp() * 1000L;
            }
        });
        // 4. 将流转换成表，定义时间特性
        Table dataTable = tableEnv.fromDataStream(dataStream, "id, timestamp as ts, temperature as temp, rt.rowtime");

        dataTable.printSchema();

        tableEnv.createTemporaryView("sensor", dataTable);
        // 5. 窗口操作
        // 5.1 Group Window  HOP
        // HOP_START
        // HOP_END

        // table API
        Table resultTable = dataTable.window(Slide.over("10.minutes").every("5.minutes").on("rt").as("w")).groupBy("id, w").select("id, id.count, temp.avg, w.end");
        //tableEnv.toAppendStream(resultTable, Row.class).print("result:");

        // SQL
        Table resultSqlTable = tableEnv.sqlQuery("select id, count(id) as cnt, avg(temp) as avgTemp, hop_end(rt, interval '10' minute, interval '5' minute) from sensor group by id, hop(rt, interval '10' minute, interval '5' minute)");
        tableEnv.toRetractStream(resultSqlTable, Row.class).print("sql:");

        env.execute();
    }
}
